//
//  HJRegisterViewController.m
//  Sneakers
//
//  Created by 胡光健 on 2017/9/28.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HJRegisterViewController.h"
#import "HJPasswordViewController.h"

@interface HJRegisterViewController ()
@property (weak, nonatomic) IBOutlet UIView *superView;
@property (weak, nonatomic) IBOutlet UITextField *editPhone;
@property (weak, nonatomic) IBOutlet UITextField *codeNo;
@property (weak, nonatomic) IBOutlet UIButton *btnCodel;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (nonatomic, assign) NSInteger timeout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *btnW;
@property(nonatomic,strong)NSNumber * code;
@end

@implementation HJRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.superView.layer.borderWidth = 1.0;
    self.superView.layer.borderColor = HJColor(192, 204, 218).CGColor;
    self.editPhone.font = HJFontSize(mScreenWidth/414 *19);
    self.codeNo.font = HJFontSize(mScreenWidth/414 *19);
    self.btnW.constant =mScreenWidth/414*80;
    [self configUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(close) name:@"NOTIFICATION_CLOSE_B" object:nil];
}

- (IBAction)sendCode:(UIButton *)sender {
    [self HTTPSmsCode:sender];
}

- (void)HTTPSmsCode:(UIButton *)btn {
    NSNumber * type;
    if ([self.navTitle isEqualToString:@"注册"]) {
        type = @1;
    }else {
        type = @0;
    }
    [TZHttpTool post:SendSms params:@{ @"mobile" : self.editPhone.text,@"type": type} success:^(NSDictionary *result) {
        [self showSuccessHUDWithStr:@"验证码发送成功"];
        [self countDown:btn];
        self.code = result[@"data"][@"code"];
        NSLog(@"验证码===%@",self.code);
    } failure:^(NSString *msg) {
        [self showErrorHUDWithError:msg];
    }];
}
-(void)close{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)configUI {
    [self configTextField];
    [self configBtnSmsCode];
}

- (void)configTextField {
    [[self.editPhone.rac_textSignal filter:^BOOL(NSString*text){
        return text.length >= 11;
    }] subscribeNext:^(NSString *text){
        self.editPhone.text = [text substringToIndex:11];
    }];
    
    [[self.codeNo.rac_textSignal filter:^BOOL(NSString*text){
        return text.length >= 4;
    }] subscribeNext:^(NSString *text){
        self.codeNo.text = [text substringToIndex:4];
    }];
}
- (void)configBtnSmsCode {
    RAC(self.btnCodel, userInteractionEnabled) = [RACSignal combineLatest:@[self.editPhone.rac_textSignal] reduce:^id(NSString *phone) {
        if ([CommonTools isMobileNumber:phone]) {
            if (_timeout <= 0) { // 上一个验证码的倒计时已经结束 或未开始 才可以获取新的验证码
                [self.btnCodel setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                self.btnCodel.backgroundColor = HJColor(93, 188, 255);
                return @YES;
            } else {
                return @NO;
            }
        } else {
            if (phone.length >= 11) {
                [self showErrorHUDWithError:@"您填写的手机号不正确！"];
            }
            [self.btnCodel setTitleColor:HJColor(165, 170, 180) forState:UIControlStateNormal];
            self.btnCodel.backgroundColor = HJColorRGB(250);
            return @NO;
        }
    }];
}
     
- (IBAction)nextOneBtn:(UIButton *)sender {
    if ([self.navTitle isEqualToString:@"注册"]) {
        [self pushPasswordWithType:passwordType navTitle:@"注册"];
    }else {
        [self pushPasswordWithType:forgotpassworType navTitle:@"忘记密码"];
    }
}

-(void)pushPasswordWithType:(passwordWithforgotType)type navTitle:(NSString *)navTitle {
    if ([self.code isEqual:self.codeNo.text.numberValue]) {
        HJPasswordViewController * passwordVC = [[HJPasswordViewController alloc]init];
        passwordVC.type = type;
        passwordVC.navTitle = navTitle;
        passwordVC.phone = self.editPhone.text;
        passwordVC.code = self.codeNo.text;
        [self.navigationController pushViewController:passwordVC animated:YES];
    }else {
        if ([self.editPhone.text isEqualToString:@""]) {
             [self showErrorHUDWithError:@"请输入手机号码"];
            return;
        }
        [self showErrorHUDWithError:@"验证码不正确"];
    }
}
#pragma mark - Private Methods
- (void)countDown:(UIButton *)btn {
    _timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (_timeout <= 0) {
            // 倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                btn.backgroundColor = HJColor(93, 188, 255);
                btn.userInteractionEnabled = YES;
                [btn setTitleColor:HJColorRGB(255) forState:UIControlStateNormal];
                [btn setTitle:@"发送" forState:UIControlStateNormal];
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"%.2ld秒", (long)_timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                [btn setBackgroundColor:HJColorRGB(250)];
                btn.userInteractionEnabled = NO;
                [btn setTitleColor:HJColor(165, 170, 180) forState:UIControlStateNormal];
                [btn setTitle:strTime forState:UIControlStateNormal];
            });
            _timeout--;
        }
    });
    dispatch_resume(_timer);
}
@end
